package com.yuncheng.spcyApi.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 转码签章-工具
 */
public class HncaTool {
    private static final Logger log = LoggerFactory.getLogger(HncaTool.class);

    public static final String url = "http://newsign.hnca.com.cn/CouldSignSystem/hc/api/server/serverStamp";
//    public static final String appId = "196A5A4F3ED4913D07EB2FE9B44AD6F8"; // 旧的appid
    public static final String appId = "CF69EC2E8A95A0E8FEAA4DDED2261D84"; // 新的appid

    public static String FileEncodeBase64(String filepath) {
        File file = new File(filepath);
        try {
            InputStream fr = new FileInputStream(file);
            byte[] b = new byte[(int) file.length()];
            fr.read(b);
            fr.close();

            String s = new BASE64Encoder().encode(b);
            return s;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }

    public static void decoderBase64File(String base64Code, String targetPath) throws IOException {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    public  static String VerifySign(String docBase64,String filepath) {
        docBase64= FileEncodeBase64(filepath);
        String RequestId = String.valueOf(java.util.UUID.randomUUID());
        RequestId = RequestId.substring(0, 8);

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("RequestId", RequestId);
        jsonObj.put("DocData", docBase64);

        String json = jsonObj.toString();
        long startTime = System.currentTimeMillis();
        String res = PostJson(url,json);
        long endTime = System.currentTimeMillis();
        float seconds = (endTime - startTime) / 1000F;
        log.info("服务器验证耗时：{}",Float.toString(seconds));

        return res;
    }

    public static String ServerSign(String docBase64,String ruleListStr) {

        String businessNum = String.valueOf(java.util.UUID.randomUUID());
        businessNum = businessNum.substring(0, 8);

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("BusinessNum", businessNum); // 流水号，不固定20位以内数字或英文字符，重复的流水号会导致合并签章失败
        jsonObj.put("appId", appId); // 固定值   bc333fe259054915bb40c6c206039389
        JSONObject documentInfo = new JSONObject();
        documentInfo.put("docuName", "testdoc.pdf"); // 文档名称
        documentInfo.put("fileDesc", ""); // 文档说明
        documentInfo.put("docBase64", docBase64); // 文档base64编码  docBase64
        jsonObj.put("documentInfo", documentInfo);

        JSONArray ruleList = new JSONArray(); // 签章规则，应用程序根据需要动态添加内容
        String ruleLists[] = ruleListStr.split(",");
        for (String string : ruleLists) {
            ruleList.add(string);
        }

        jsonObj.put("ruleList", ruleList);

        String rule = "";
        for (int i = 0; i < ruleList.size(); i++) {
            rule = rule + ruleList.getString(i);
        }

        String strJson = jsonObj.toString();
//        log.info(strJson);
        String res = PostJson(url,strJson);
        res = res.trim();
        return res;
    }

    private static String PostJson(String urlpath, String json) {
        String strUrl = urlpath;

        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1 ");
            conn.setRequestProperty("Content-type", "application/json");
            conn.setRequestProperty("Accept-Charset", "utf-8");

            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(json.getBytes("utf-8"));
            out.flush();
            out.close();

            InputStream instream = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "utf-8"));

            String line = "";
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                line = new String(line.getBytes(), "utf-8");
                sb.append(line);
            }

            reader.close();
            conn.disconnect();

            return sb.toString();
        } catch (Exception ex) {
            log.error("发送报文异常：{}",ex.getMessage());
            return "";
        }
    }


    public static void main(String[] args){
        String docBase64 = "";
        String ruleList = "HNCA_16766256244972";//可用 HNCA_16715070970910
//        String FilePath="D:\\data\\java\\uploadfiles\\jpImg\\HZPCY202100073268A15CD5BEF4953E44F94D6CCFC721\\baidu4.pdf";
        String FilePath = "C:/Users/86198/Downloads/af.pdf";
        //1.验证是否有pdf
        File file=new File(FilePath);
        if (!file.exists()) {
            System.out.println("未找到pdf");
            return;
        }
        //2.转码签章
        docBase64 = HncaTool.FileEncodeBase64(FilePath); // 960KB
        System.out.println("开始构造云签章请求");
        String res = HncaTool.ServerSign(docBase64,ruleList); // 构造云签章请求并等待服务器返回
        System.out.println(res);

        //3.解析签章结果
        try {
            JSONObject jsonRes = JSONObject.parseObject(res);

            if (jsonRes.getString("ErrorCode").equals("0")) { // 获取错误码
                String fileData = jsonRes.getString("SignDoc"); // 获取已签章文件的base64编码
                // 保存文件
                HncaTool.decoderBase64File(fileData, FilePath);
                res =  HncaTool.VerifySign(docBase64,FilePath);
               /* spBasic.setLccb_dzbgqzsj(new Date());
                spBasic.setLccb_dzbgshzt("已签章");
                dao.attachDirty(spBasic);*/
            } else {

                System.out.println("出现错误");
                System.out.println(jsonRes.getString("ErrorCode"));
                System.out.println(jsonRes.getString("ErrorMsg")); // 打印错误信息
               /* msg = "签章错误："+jsonRes.getString("ErrorMsg");
                state="0";
                break;*/
            }
        } catch (Exception ex) {
            System.out.println("错误数据：" + res);
           /* msg = "签章错误："+res;
            state="0";
            break;*/
        }
    }

}
